package com.linxuan.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.linxuan.reggie.common.CustomException;
import com.linxuan.reggie.dao.CategoryMapper;
import com.linxuan.reggie.entity.Category;
import com.linxuan.reggie.entity.Dish;
import com.linxuan.reggie.entity.Setmeal;
import com.linxuan.reggie.service.CategoryService;
import com.linxuan.reggie.service.DishService;
import com.linxuan.reggie.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Autowired
    private DishService dishService;

    @Autowired
    private SetmealService setmealService;

    @Override
    public boolean removeById(Long id) {

        log.info("查看dish和setmeal表有无关联的category_id");

        // 构造菜品查询构造器
        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishLambdaQueryWrapper.eq(Dish::getCategoryId, id);
        // 查询当前分类是否关联菜品,如果已经关联，抛出业务异常
        if (dishService.count(dishLambdaQueryWrapper) > 0) {
            // 已经关联菜品，抛出业务异常
            throw new CustomException("已经关联菜品，不能删除");
        }

        LambdaQueryWrapper<Setmeal> setmealLambdaQueryWrapper = new LambdaQueryWrapper<>();
        setmealLambdaQueryWrapper.eq(Setmeal::getCategoryId, id);
        // 查询当前分类是否关联套餐,如果已经关联，抛出业务异常
        if (setmealService.count(setmealLambdaQueryWrapper) > 0) {
            // 已经关联套餐，抛出业务异常
            throw new CustomException("已经关联套餐，不能删除");
        }

        // 正常删除分类
        return super.removeById(id);
    }
}
